package com.gz.mylife.app;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.adapter.BaseAdapterHelper;
import com.gz.mylife.adapter.QuickAdapter;
import com.gz.mylife.im.MessageChannel;
import com.gz.mylife.im.MessageChannel.Meta;
import com.gz.mylife.util.DateTimePickDialogUtil;
import com.gz.mylife.widget.FooterView;
import com.gz.mylife.widget.LoadingCover;
import com.gz.mylife.widget.OfflineDialog;
import com.gz.mylife.widget.FooterView.OnFooterViewRefreshListener;
import com.gz.mylife.widget.LoadingCover.OnLoadingCoverRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zl.smartmall.library.IGZAddress;
import com.zl.smartmall.library.ISmartMall;
import com.zl.smartmall.library.listener.GetParticipationListener;
import com.zl.smartmall.library.listener.RequestCode;
import com.zl.smartmall.library.po.ParticipationInfo;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.Tools;

/**
 * 
 * @author 陈希然
 * ┏┓　　　┏┓
┏┛┻━━━┛┻┓
┃　　　　　　　┃ 　
┃　　　━　　　┃
┃　┳┛　┗┳　┃
┃　　　　　　　┃
┃　　　┻　　　┃
┃　　　　　　　┃
┗━┓　　　┏━┛
     ┃　　　┃   草泥马保佑　　　　　　　　
     ┃　　　┃   代码无BUG！
     ┃　　　┗━━━┓
     ┃　　　　　　　┣┓
     ┃　　　　　　　┏┛
     ┗┓┓┏━┳┓┏┛
        ┃┫┫　 ┃┫┫
        ┗┻┛　 ┗┻┛
 *
 */
public class FragmentParticipation extends Fragment implements OnFooterViewRefreshListener, OnLoadingCoverRefreshListener, OnRefreshListener<ListView>, OnItemClickListener,Observer{

	private static final String TAG = FragmentParticipation.class.getSimpleName();
	
	private Context mContext;
	private QuickAdapter<ParticipationInfo> mAdapter;

	private FooterView mFooterView;
	private LoadingCover mLoadingCover;
	private OfflineDialog mOfflineDialog;
	private PullToRefreshListView mPullList;
	private View mConvertView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		CrashHandler.d(TAG, TAG + " onCreate");
		MessageChannel.get().register(MessageChannel.RMESSAGE, this);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		CrashHandler.d(TAG, TAG + " onCreateView");
		if(mConvertView == null){
			CrashHandler.d(TAG, "convertView is null, init the whole elements");
			mConvertView = inflater.inflate(R.layout.fragment_participation, container, false);
			init(inflater);
		}
//		((BaseActionBarActivity) getActivity()).mActionBar.setTitle("营养专栏");
		
		return mConvertView;
	}
	
	@Override
	public void onDetach() {
		// TODO Auto-generated method stub
		super.onDetach();
//        try {
//            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
//            childFragmentManager.setAccessible(true);
//            childFragmentManager.set(this, null);
//        } catch (NoSuchFieldException e) {
//            throw new RuntimeException(e);
//        } catch (IllegalAccessException e) {
//            throw new RuntimeException(e);
//        }
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		CrashHandler.d(TAG, TAG + " onDestroy");
		MessageChannel.get().unregister(MessageChannel.RMESSAGE, this);
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		CrashHandler.d(TAG, TAG + " onDestroyView");
		((ViewGroup) mConvertView.getParent()).removeView(mConvertView);
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		CrashHandler.d(TAG, TAG + " onPause");
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		CrashHandler.d(TAG, TAG + " onResume");
	}


	
	private void init(LayoutInflater inflater){
		mContext = getActivity().getApplicationContext();
		mAdapter = buildAdapter();
		mFooterView = (FooterView) inflater.inflate(R.layout.footer_view, null);
		mFooterView.setOnFooterViewRefreshListener(this);
		
		mLoadingCover = (LoadingCover) mConvertView.findViewById(R.id.layout_loading_cover);
		mLoadingCover.setOnLoadingCoverRefreshListener(this);
		mOfflineDialog = (OfflineDialog) inflater.inflate(R.layout.offline_dialog, null);
		mPullList = (PullToRefreshListView) mConvertView.findViewById(R.id.list);
		mPullList.getRefreshableView().addFooterView(mFooterView);
		mPullList.setAdapter(mAdapter);
		mPullList.setOnRefreshListener(this);
		mPullList.setOnItemClickListener(this);
		mPullList.setOnScrollListener(mFooterView);
		
		onLoadingCoverRefresh();
	}

	@Override
	public void onFooterViewRefresh() {
		// TODO Auto-generated method stub
		ISmartMall.getInstance().getParticipation(
				IGZAddress.getInstance().getCurrentCommunityID(),
				mAdapter.getItem(mAdapter.getCount() - 1).getParticationId(), 
				buildListener(RequestCode.SCROLL));
	}

	@Override
	public void onLoadingCoverRefresh() {
		// TODO Auto-generated method stub
		ISmartMall.getInstance().getParticipation(
				IGZAddress.getInstance().getCurrentCommunityID(), 
				0, 
				buildListener(RequestCode.PULL));
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		ISmartMall.getInstance().getParticipation(
				IGZAddress.getInstance().getCurrentCommunityID(),
				0, 
				buildListener(RequestCode.PULL));
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		ParticipationInfo model = mAdapter.getItem((int) id);
		if (model.getType() == 1) {// 系统通知
				Intent intent = new Intent(getActivity(), Systemnofity.class);
				intent.putExtra("titles", "参与");
				intent.putExtra("title", model.getTitle());//系统通知的标题
				intent.putExtra("content", model.getContent());//系统通知内容
				intent.putExtra("datetime", model.getDateline());
				intent.putExtra("picture", model.getPicture());
				startActivity(intent);
		}
		if (model.getType() == 2) {
			try {
				JSONObject object = new JSONObject(model.getLinkData());
				Intent newsIntent = new Intent(getActivity(), Browser.class);
				newsIntent.putExtra("url", object.getString("url"));
				newsIntent.putExtra("title", "活动详情");
				startActivity(newsIntent);
			} catch (JSONException e) {
				CrashHandler.e(e);
			}
			
		} else if(model.getType() == 3) {//商品列表
			String[] split = model.getLinkData().split("\\|");
			Intent intent = new Intent(mContext, FragmentMallBrandedProductsActivity.class);
			intent.putExtra("brandId", Integer.valueOf(split[0]));
			intent.putExtra("name", split[1]);
			startActivity(intent);
		
		}else if(model.getType() == 4) {//商品详情
			String[] split = model.getLinkData().split("\\|");
			Intent intent = new Intent(mContext, ProductDetail.class);
			intent.putExtra("shopId", Integer.valueOf(split[0]));
			intent.putExtra("productId", Integer.valueOf(split[1]));
			startActivity(intent);
		}
	}
	
	private QuickAdapter<ParticipationInfo> buildAdapter() {
		return new QuickAdapter<ParticipationInfo>(mContext, R.layout.participation_item, new ArrayList<ParticipationInfo>()) {

			@Override
			protected void convert(BaseAdapterHelper helper, ParticipationInfo item) {
				// TODO Auto-generated method stub
				helper.setText(R.id.tv_date, Tools.formatTimeStampString(mContext, item.getDateline(), false))
					  .setText(R.id.tv_short_date, Tools.formatTimeStampString(mContext, item.getDateline(), false))
					  .setText(R.id.tv_title, item.getTitle())
					  .setText(R.id.tv_content, item.getContent())
					  .setImageUrl(R.id.iv_picture, item.getPicture());
			}
		};
	}
	
	private GetParticipationListener buildListener(RequestCode requestCode) {
		return new GetParticipationListener(requestCode) {
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed();
				mFooterView.onRefreshFailed();
				if(mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshFailed();
				}
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mOfflineDialog.show();
				mLoadingCover.onRefreshFailed(Define.MSG_OFFLINE_ERROR);
				if(mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshFailed();
				}
			}
			
			@Override
			public void onNoMoreData() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed(Define.MSG_NOTHING);
				mFooterView.onRefreshComplete();
				mPullList.setOnScrollListener(null);
				if(mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshSuccess();
				}
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onResponseSuccess(List<ParticipationInfo> participationInfos) {
				// TODO Auto-generated method stub
				if(getRequestCode() == RequestCode.PULL) {
					mAdapter.clear();
				}
				mAdapter.addAll(participationInfos);
				if (participationInfos.size() < Define.LISTVIEW_ITEM_MIN_SIZE) {
					mFooterView.onRefreshComplete();
					mPullList.setOnScrollListener(null);
					
				} else {
					mFooterView.onRefreshSuccess();
					mPullList.setOnScrollListener(mFooterView);
				}
				if(mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshSuccess();
				}
				mLoadingCover.onRefreshSuccess();
			}
		};
	}
	
	public void autoRefresh(){
		onLoadingCoverRefresh();
		mAdapter.clear();
		mLoadingCover.setVisibility(View.VISIBLE);
	}

	@Override
	public void update(Observable arg0, Object data) {
		// TODO Auto-generated method stub
		Meta meta = (Meta) data;
		if(meta.msgType == MessageChannel.RMESSAGE){
			ISmartMall.getInstance().getParticipation(
					IGZAddress.getInstance().getCurrentCommunityID(),
					0, 
					buildListener(RequestCode.PULL));
		}
	}

}
